package at.fhv.framework;

import java.util.ArrayList;
import java.util.List;

import at.fhv.framework.events.ImageEvent;
import at.fhv.framework.listeners.ImageProcessingListener;
import at.fhv.framework.listeners.RefireListener;

/**
 * This class processes common actions for all image processing beans. Use this
 * class in image processing beans by composition.
 * 
 * @author Michael Sieber
 */
public final class CommonImageProcessingHelper {
	private List<ImageProcessingListener> _listeners;
	private List<RefireListener> _refire;
	private RefireListener _owner;

	/**
	 * Create a new CommonImageProcessingHelper
	 * 
	 * @param owner The owner of this object
	 */
	public CommonImageProcessingHelper(RefireListener owner) {
		_owner = owner;
	}

	/**
	 * Add an image processing listener
	 * 
	 * @param listener The listener to add
	 */
	public void addImageProcessingListener(ImageProcessingListener listener) {
		if (_listeners == null) {
			_listeners = new ArrayList<ImageProcessingListener>();
		}

		listener.addRefireListener(_owner);
		_listeners.add(listener);
	}

	/**
	 * Remove an image processing listener
	 * 
	 * @param listener The listener to remove
	 */
	public void removeImageProcessingListener(ImageProcessingListener listener) {
		if (_listeners.contains(listener)) {
			listener.removeRefireListener(_owner);
			_listeners.remove(listener);
		}
	}

	/**
	 * Fire the image processing events to all listeners.
	 * 
	 * @param event The event to fire
	 */
	public void fireImageProcessingEvent(ImageEvent event) {
		if (_listeners != null) {
			for (ImageProcessingListener listener : _listeners) {
				listener.imageChanged(event);
			}
		}
	}

	/**
	 * Add a refire listener
	 * 
	 * @param listener The listener to add
	 */
	public void addRefireListener(RefireListener listener) {
		if (_refire == null) {
			_refire = new ArrayList<RefireListener>();
		}

		_refire.add(listener);
	}

	/**
	 * Remove a refire listener
	 * 
	 * @param listener The listener to remove
	 */
	public void removeRefireListener(RefireListener listener) {
		if (_refire.contains(listener)) {
			_refire.remove(listener);
		}
	}

	/**
	 * Fire the refire event for all refire listeners
	 */
	public void fireRefireEvent() {
		fireRefireEvent(null);
	}

	/**
	 * Fire the refire event but exclude a specific refire listener
	 * 
	 * @param exclude The refire listener to exclude
	 */
	public void fireRefireEvent(RefireListener exclude) {
		if (_refire != null) {
			for (RefireListener refire : _refire) {
				if (!refire.equals(exclude)) {
					refire.refire();
				}
			}
		}
	}
}
